<?php
namespace App\Providers\Services;

use Illuminate\Support\ServiceProvider;
use Doctrine\Common\Cache\PredisCache;
use EasyWeChat\Foundation\Application;
use Illuminate\Support\Arr;

class WeChatServiceProvider extends ServiceProvider
{
    protected $defer = false;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Application::class, function ($app) {
            $config = $app['config']['wechat'];
            if (empty($config)) {
                throw new \Exception('config wechat first');
            }
            return new Application($config);
        });

        $this->app->singleton('wechat.plateform', function ($app) {
            $config = $app['config']['plateform-wechat'];
            $debug = $app['config']['app.debug'];

            $application = new Application([
                'debug' => $debug,
                'app_id'  => Arr::get($config, 'app_id'),
                'secret'  => Arr::get($config, 'app_secret'),
            ]);

            $client = $app['redis']->connection()->client();
            $driver = new PredisCache($client);

            $application->offsetSet('cache', $driver);

            return $application;
        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        //
        return [
            Application::class,
        ];
    }
}
